<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            var lastStoneWeightII = function (stones) {
                stones.sort((a, b) => a - b)
                let sum = stones.reduce((pre, item) => (pre += item))
                let bagSize = parseInt(sum / 2)
                let dp = new Array(bagSize + 1).fill(0)
                for (let i = 0; i < dp.length; i++) {
                    for (let j = bagSize; j >= stones[i]; j--) {
                        dp[j] = Math.max(dp[j], dp[j - stones[i]] + stones[i])
                    }
                }
                return sum - 2 * dp[bagSize]
            }
        </script>
    </body>
</html>
